package com.iyao_app.mvp.info;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.callback.ItemDragAndSwipeCallback;
import com.chad.library.adapter.base.listener.OnItemDragListener;
import com.iyao_app.R;
import com.iyao_app.adapter.PublishAdapter;
import com.iyao_app.base.BaseActivity;
import com.iyao_app.entry.ResultModel;
import com.iyao_app.entry.UpdateImage;
import com.iyao_app.entry.UploadImage;
import com.iyao_app.entry.User;
import com.iyao_app.http.NetCallBack;
import com.iyao_app.http.NetUtils;
import com.iyao_app.http.RequestUrl;
import com.iyao_app.util.Contants;
import com.iyao_app.util.DbUtil;
import com.iyao_app.util.MessageEvent;
import com.iyao_app.util.PickImageLoader;
import com.iyaowoqu.base_library.util.ImageUtils;
import com.iyaowoqu.base_library.util.LogUtil;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import top.zibin.luban.Luban;

/**
 * 作者 :  胡家兵
 * 时间 :  2017/12/7.
 */

public class VisionImpressionActivity extends BaseActivity {

    @BindView(R.id.tv_title)
    TextView mTvTitle;
    @BindView(R.id.rv_publish)
    RecyclerView mRvPublish;


    private PublishAdapter adapter;
    private ImagePicker imagePicker;
    final int MAX_COUNT = 6;
    final int IMAGE_PICKER = 1;
    int limit = 0;
    private User user;
    private Map<Integer, UpdateImage> map;
    private List<String> imageList;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_vision_impression);
        ButterKnife.bind(this);
        initData();
    }

    @OnClick({R.id.iv_back, R.id.iv_next})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_next:
                MessageEvent messageEvent = new MessageEvent(MessageEvent.USER_INFO_REFUSH);
                EventBus.getDefault().post(messageEvent);
                check();
                break;
        }
    }

    private void initPicker() {
        imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new PickImageLoader());   //设置图片加载器
        imagePicker.setShowCamera(true);  //显示拍照按钮
        imagePicker.setCrop(false);        //允许裁剪（单选才有效）
        imagePicker.setMultiMode(true);
        imagePicker.setSelectLimit(MAX_COUNT);    //选中数量限制

    }

    private void initData() {
        user = DbUtil.getUser();
        LogUtil.e("===" + user.toString());
        String s = user.visionImpression;
        if (!TextUtils.isEmpty(s)) {
            imageList = JSON.parseArray(s, String.class);
        }
        initPicker();
        StaggeredGridLayoutManager manager = new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL);
        mRvPublish.setLayoutManager(manager);

        adapter = new PublishAdapter(null);
        mRvPublish.setAdapter(adapter);
        if (imageList != null && imageList.size() > 0) {
            adapter.addData(imageList);
        }
        if (imageList == null || imageList.size() != 6) {
            adapter.addData("mipmap");
        }

        ItemDragAndSwipeCallback mItemDragAndSwipeCallback = new ItemDragAndSwipeCallback(adapter);
        ItemTouchHelper mItemTouchHelper = new ItemTouchHelper(mItemDragAndSwipeCallback);
        mItemTouchHelper.attachToRecyclerView(mRvPublish);
        adapter.enableDragItem(mItemTouchHelper);

        adapter.setOnItemDragListener(new OnItemDragListener() {
            @Override
            public void onItemDragStart(RecyclerView.ViewHolder viewHolder, int pos) {
                LogUtil.e("==onItemDragStart=");

            }

            @Override
            public void onItemDragMoving(RecyclerView.ViewHolder source, int from, RecyclerView.ViewHolder target, int to) {
                LogUtil.e("==onItemDragMoving=");
            }

            @Override
            public void onItemDragEnd(RecyclerView.ViewHolder viewHolder, int pos) {
                LogUtil.e("==onItemDragEnd=");
            }
        });
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                LogUtil.e("====" + position);
                String item = (String) adapter.getItem(position);
                if ("mipmap".equals(item)) {
                    if (imagePicker != null) {
                        limit = MAX_COUNT - adapter.getData().size() + 1;
                        imagePicker.setSelectLimit(limit);
                    }
                    Intent intent = new Intent(VisionImpressionActivity.this, ImageGridActivity.class);
                    startActivityForResult(intent, IMAGE_PICKER);
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            if (data != null && requestCode == IMAGE_PICKER) {
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                ImageItem imageItem = images.get(0);
                for (int i = 0; i < adapter.getData().size(); i++) {
                    if ("mipmap".equals(adapter.getData().get(i))) {
                        adapter.remove(i);
                        adapter.notifyItemRemoved(i);
                    }
                }
                for (ImageItem image : images) {
                    adapter.addData(image.path);
                }
                if (adapter.getData().size() < 6) {
                    adapter.addData("mipmap");
                }
                adapter.notifyDataSetChanged();
                LogUtil.e("===" + imageItem.path);
            } else {
                Toast.makeText(this, "没有数据", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void check() {
        if (user == null) {
            Toast.makeText(this, "请登录", Toast.LENGTH_SHORT).show();
            return;
        }
        if (adapter.getData().size() == 1) {
            Toast.makeText(this, "请至少添加一张图片", Toast.LENGTH_SHORT).show();
            return;
        }
        showDialog();
        boolean isUpdate = true;
        for (int i = 0; i < adapter.getData().size(); i++) {
            String image = adapter.getData().get(i);
            if (!image.startsWith("http") && !"mipmap".equals(image)) {
                isUpdate = false;
                upLoadImage(i, image);
            } else {
                LogUtil.e("不需要上传");
            }
        }
        if (isUpdate) {
            publish();
        }
    }

    private void upLoadImage(final int pos, final String updateImage) {
        Flowable.just(updateImage)
                .observeOn(Schedulers.io())
                .map(new Function<String, File>() {
                    @Override
                    public File apply(String s) throws Exception {
                        return Luban.with(VisionImpressionActivity.this).load(s).get().get(0);
                    }
                }).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<File>() {

                    @Override
                    public void accept(File file) throws Exception {
                        int[] imageInfo = ImageUtils.getImageWidthHeight(file);
                        LogUtil.e(imageInfo[0] + "=====" + imageInfo[1]);

                        final HashMap<String, Object> hashMap = new HashMap<>();
//                        File value = new File(updateImage.image);
                        hashMap.put("file", file);
                        NetUtils.getInstance().uploadImage(RequestUrl.UPLOAD_FILE, imageInfo[0], imageInfo[1], hashMap, new NetCallBack() {
                            @Override
                            public void onSuccess(final String message, final int code, String response, final ResultModel model) {
                                if (code == Contants.SUCCESS_CODE) {

                                    UploadImage modelModel = model.getModel();
                                    if (modelModel != null && !TextUtils.isEmpty(modelModel.getFileUrl())) {
                                        adapter.setData(pos, modelModel.getFileUrl());
                                        publish();
                                    }
                                } else {
                                    closeDialog();
                                    if (!TextUtils.isEmpty(message)) {

                                    }
                                }
                            }

                            @Override
                            public void onFail(String message, int code) {
                                Toast.makeText(VisionImpressionActivity.this, "上传图片失败", Toast.LENGTH_SHORT).show();
                                closeDialog();
                            }
                        }, UploadImage.class);
                    }
                });

    }

    public void publish() {

        boolean isSuccess = true;
        final List<String> list = new ArrayList<>();
        for (int i = 0; i < adapter.getData().size(); i++) {
            if (!"mipmap".equals(adapter.getData().get(i))) {
                list.add(adapter.getData().get(i));
                if (!adapter.getData().get(i).startsWith("http")) {
                    isSuccess = false;
                }
            }
        }
        if (isSuccess) {
            NetUtils.getInstance().visualImpressions(user.id, list, new NetCallBack() {
                @Override
                public void onSuccess(String message, int code, String response, ResultModel model) {
                    closeDialog();
                    if (code == Contants.SUCCESS_CODE) {

                        String s = JSON.toJSONString(list, true);
                        user.visionImpression = s;
                        DbUtil.updateUserInfo(user);
                        MessageEvent messageEvent = new MessageEvent(MessageEvent.USER_INFO_REFUSH);
                        EventBus.getDefault().post(messageEvent);
                        finish();
                    } else {
                        if (!TextUtils.isEmpty(message)) {
                            Toast.makeText(VisionImpressionActivity.this, message, Toast.LENGTH_SHORT).show();
                        }
                    }
                }

                @Override
                public void onFail(String message, int code) {
                    closeDialog();
                }
            }, null);
        } else {
            return;
        }
    }

}
